package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.entity.Message
import cn.exrick.xboot.base.entity.SecurityAdvisorServiceEnterprise
import cn.exrick.xboot.base.mapper.MessageMapper
import cn.exrick.xboot.base.service.IEnterpriseUserService
import cn.exrick.xboot.base.service.IMessageService
import cn.exrick.xboot.base.service.ISecurityAdvisorService
import cn.exrick.xboot.base.service.ISecurityAdvisorServiceEnterpriseService
import cn.exrick.xboot.base.vo.MessageDetailVo
import cn.exrick.xboot.base.vo.MessageListVo
import cn.exrick.xboot.base.vo.MessageVo
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.service.UserService
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import javax.annotation.Resource

/**
 * 信息接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IMessageServiceImpl : ServiceImpl<MessageMapper?, Message?>(), IMessageService {


    @Autowired
    private var securityUtil: SecurityUtil? = null
    @Autowired
    private var iSecurityAdvisorService: ISecurityAdvisorService? = null
    @Autowired
    private lateinit var iEnterpriseUserService: IEnterpriseUserService
    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var iSecurityAdvisorServiceEnterpriseService: ISecurityAdvisorServiceEnterpriseService


    override fun sendMessage(message: Message): Result<Any?>? {

        return try {

            save(Message().apply {

                type = 2
                enterpriseId = iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id)
            })
            ResultUtil.success("发送成功")
        }catch (e : Exception) {

            ResultUtil.error(e.message)
        }
    }

    override fun createEnterpriseMessage(securityAdvisorId: Array<out String>): Result<Any?>? {

        return try {

            securityAdvisorId.forEach {

                iSecurityAdvisorServiceEnterpriseService.getOne(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java)
                        .eq(SecurityAdvisorServiceEnterprise::enterpriseUserId, iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id))
                        .eq(SecurityAdvisorServiceEnterprise::createBy, iSecurityAdvisorService!!.getUserIdBySecurityId(it) )
                        .eq(SecurityAdvisorServiceEnterprise::serviceStatus, true))?.run {

                    return ResultUtil.error(203, "当前安全顾问正在为贵公司服务!")
                }

                getOne(KtQueryWrapper(Message::class.java).eq(Message::enterpriseId, iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id))
                        .eq(Message::receiveUserId, iSecurityAdvisorService!!.getById(it)?.userId)
                        .eq(Message::isRead, false))?.run {
                   return ResultUtil.error(204, "已经发送过邀请信息")
                }

                save(Message().apply {

                    type = 1
                    title = "企业应聘消息"
                    enterpriseId = iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id)
                    content = securityUtil!!.currUser.username + "企业应聘你成为他(她)企业安全顾问"
                    receiveUserId = iSecurityAdvisorService!!.getById(it)?.userId
                })
            }
            ResultUtil.success("发送成功")
        }catch (e : Exception) {

            ResultUtil.error(e.message)
        }
    }

    override fun getMyMessageList(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(Message::class.java).eq(Message::createBy, securityUtil!!.currUser.id)
                .orderByDesc(Message::createTime)))?.run {

            val result:MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = this.size
            result["content"] = PageUtil.listToPage(pageVo, this)
            ResultUtil.data(result, "获取信息成功！")
        } ?: ResultUtil.error(201,"暂无数据")
    }

    override fun getMyReceiveMessageList(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(Message::class.java).eq(Message::receiveUserId, securityUtil!!.currUser.id)
                .eq(Message::type, 1)
                .eq(Message::isRead, false)
                .orderByDesc(Message::createTime)))?.run {

            val result:MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = this.size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { MessageVo().apply {

                ToolUtil.copyProperties(it, this)
                enterpriseName = iEnterpriseUserService.getById(it?.enterpriseId)?.companyName
                avatar = iEnterpriseUserService.getById(it?.enterpriseId)?.avatar
                typeStr = when (type) {
                    1 -> {
                        "企业应聘"
                    }
                    else -> {
                        "其他消息"
                    }
                }
            } })
            ResultUtil.data(result, "获取信息成功！")
        } ?: ResultUtil.error(201,"暂无数据")
    }

    override fun getMyAppMessageList(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(Message::class.java).eq(Message::receiveUserId, securityUtil!!.currUser.id)
                .ne(Message::type, 1)
                .orderByDesc(Message::createTime)))?.run {

            val result:MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = this.size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { MessageListVo().apply {

                sendUsername = if (it!!.type == 1) iEnterpriseUserService.getById(it.enterpriseId)?.companyName else userService.get(it.createBy)?.nickname
                sendUserAvatar = if (it.type == 1) iEnterpriseUserService.getById(it.enterpriseId)?.avatar else userService.get(it.createBy)?.avatar
                sendTitle = it.title
                ToolUtil.copyProperties(it, this)
            } })

            ResultUtil.data(result, "获取信息成功！")
        } ?: ResultUtil.error(201,"暂无数据！")
    }

    override fun getMyAppMessageDetail(id: String): Result<MessageDetailVo>? {

        return getById(id)?.run {

            isRead = true
            updateById(this)

            ResultUtil.data(MessageDetailVo().apply { ToolUtil.copyProperties(this@run, this) })
        } ?: ResultUtil.error(201, "不存在当前消息")
    }

    override fun getMyMessageUnReadCount(enterprise: Int): Result<Int>? {

        return ResultUtil.data(count(KtQueryWrapper(Message::class.java).eq(Message::receiveUserId, securityUtil!!.currUser.id)
                .eq(ToolUtil.isNotEmpty(enterprise), Message::type, 1)
                .eq(Message::isRead, false)))
    }

}